package com.wy.panda.filter;

import java.io.IOException;
import java.util.Random;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.wy.panda.common.util.IPUtils;

/**
 * slf4j MDC配置拦截器
 * @author wangyuan
 * @since 2021年3月24日 下午2:12:49
 */
@Order(0)
@Component
@WebFilter(filterName = "mdcLogConfigFilter", urlPatterns = "/**")
public class MDCLogConfigFilter implements Filter {
    
    private static final Logger logger = LoggerFactory.getLogger(MDCLogConfigFilter.class);
    
    private final static String REQUEST_ID = "requestId";

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        //初始化
        init(request);
        try {
            chain.doFilter(request, response);
        } finally {
            //清理
            finish();
        }
    }
    
    private void init(ServletRequest request) {
        String requestId = requestId();
        MDC.put(REQUEST_ID, requestId);
        
        if (request instanceof HttpServletRequest) {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            logger.info("remoteHost={},requestUri={}", IPUtils.getIpAddr(httpServletRequest), httpServletRequest.getRequestURI());
        } else {
            logger.info("remoteHost={}", request.getRemoteHost());
        }
    }
    
    private void finish() {
        MDC.remove(REQUEST_ID);
    }
    
    private String requestId() {
        int requestIdLength = 10;
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        sb.append(Math.abs(random.nextLong()));
        if(sb.length() < requestIdLength) {
            while(sb.length() < requestIdLength) {
                sb.append("0");
            }
        }
        return sb.substring(0, 10);
    }
}
